package com.apestech.framework.xml;

import com.alibaba.druid.pool.DruidDataSource;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.FileUtil;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.xml.modul.XmlFile;
import com.apestech.framework.xml.modul.Xml_File;
import com.apestech.framework.xml.modul.Xml_Id;
import com.apestech.framework.xml.plugin.XmlPaste;
import com.apestech.framework.xml.plugin.modul.Database;
import com.apestech.framework.xml.plugin.modul.Model;
import com.apestech.framework.xml.plugin.modul.SpecialField;
import com.apestech.framework.xml.plugin.modul.SysCondition;

import java.io.File;
import java.util.ArrayList;

/**
 * @author hup
 * @create 2019-01-23-14:57
 */
public class XmlSysConfig {
    private XmlPaste xml;
    private Database database;
    private Model model;
    private SysCondition sysCondition;
    private SpecialField specialField;

    private JSONObject xml_file=new JSONObject();
    private JSONObject xml_id=new JSONObject();
    private JSONObject xml_file_ids=new JSONObject();

    public XmlSysConfig() throws Exception {
//        InputStream ins=this.getClass().getResourceAsStream("/config/query/config/config.xml");
//        Scanner scanner = new Scanner(ins, "UTF-8");
//        String text = scanner.useDelimiter("\\A").next();
        String path=LocalVariable.getRootDir()+ File.separator+"config"+File.separator+"config.xml";
        xml=new XmlPaste(path);
    }

    public Database.DB getConfigDatabase(String db) throws Exception {
        iniConfigDatabase();
        if(db==null) db="dev.erp";
        return database.getDBById(db);
    }

    private void iniConfigDatabase() throws Exception {
        if(database==null){
            xml.setNode("database");
            xml.expain();
            database=xml.getDatabase();
        }
    }

    public String getDBProFiles(DruidDataSource ds) throws Exception {
        if(ds==null) return null;
        iniConfigDatabase();
        String url=ds.getUrl().toUpperCase();
        String username=ds.getUsername().toUpperCase();
        String password=ds.getPassword();
        ArrayList<String> klist=database.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            String k=klist.get(i);
            Database.DB db=database.getDBById(k);
            if(url.indexOf(db.getUrl().toUpperCase())>=0 && username.equals(db.getUsername().toUpperCase())
                    && password.equals(db.getPassword())){
                return k;
            }
        }
        return null;
    }

    public SpecialField.Field getSpecialField(String db) throws Exception {
        if(specialField==null){
            xml.setNode("specialField");
            xml.expain();
            specialField=xml.getSpecialField();
        }
        if(db==null) db="esb";
        return specialField.getField(db);
    }

    public Model getModel() throws Exception {
        if(model==null){
            xml.setNode("model");
            xml.expain();
            model=xml.getModel();
            model.getModel();
        }
        return model;
    }

    public SysCondition getSysCondition(SqlSession session) throws Exception {
        if(sysCondition==null){
            xml.setSession(session);
            xml.setNode("sysCondition");
            xml.expain();
            sysCondition=xml.getSysCondition();
        }
        return sysCondition;
    }

    public void setXmlFile(XmlFile xml) throws Exception {
        Xml_Id xmlid=new Xml_Id(xml.getAllid());
        xmlid.setId(xml.getId());
        xmlid.setNode(xml.getNode());
        xmlid.setNodeName(xml.getNodename());
        xmlid.setPrefix(xml.getPrefix());
        xmlid.setFile(xml.getFile());
        xml_id.put(xml.getAllid(), xmlid);
        if(xml_file.get(xml.getLfile())==null){
            Xml_File xmlfile=new Xml_File(xml.getFile());
            xmlfile.setAllid(xml.getAllid());
            xmlfile.setPrefix(xml.getLprefix());
            xmlfile.setRoot(xml.getRoot());
            xmlfile.setXml(xml.getXml());
            xml_file.put(xml.getLfile(), xmlfile);
            xml_file.put(xml.getLprefix(), xml.getLfile());
        }
        String file=xml_file_ids.getString(xml.getPrefix());
        if(file==null) file="";
        if((","+file+",").indexOf(","+xml.getPrefix()+",")<0){
            file=file+","+xml.getAllid();
            xml_file_ids.put(xml.getLprefix(), file);
        }
    }

    public XmlFile getXmlFile(String id) throws Exception {
        Xml_Id xmlid= (Xml_Id) xml_id.get(id);
        if(xmlid==null) return null;
        XmlFile xmlFile=new XmlFile(xmlid);
        Xml_File file=(Xml_File) xml_file.get(xmlid.getLfile());
        xmlFile.setRoot(file.getRoot());
        xmlFile.setXml(file.getXml());
        return xmlFile;
    }

    public Xml_File getXml_File(String file){
        Object obj=xml_file.get(file);
        if(obj==null) return null;
        if(obj instanceof String) {
            obj=xml_file.get(obj);
        }
        return (Xml_File) obj;
    }

    public String getXmlFileTxt(String file){
        Xml_File xmlFile= (Xml_File) xml_file.get(file);
        if(xmlFile==null) return null;
        return xmlFile.getXml();
    }

    public void removeXmlFile(String file){
        file=file.toLowerCase();
        if(file.indexOf(File.separator)>0){
            if(file.indexOf(".")<0) return;
            //epcAnalysisReport.query
            Xml_File xmlfile= (Xml_File) xml_file.get(file);
            if(xmlfile==null) return;
            String id=xmlfile.getPrefix();
            xml_file.remove(id);
            String f=xml_file_ids.getString(id);
            if(f!=null){
                String[] list=f.split(",");
                int len=list.length;
                for(int i=0; i<len; i++){
                    if(!"".equals(list[i]))
                        xml_id.remove(list[i]);
                }
            }
            xml_file_ids.remove(id);
            xml_file.remove(file);
        } else {
            xml_file.remove(file);
            String f=xml_file_ids.getString(file);
            if(f!=null){
                String[] list=f.split(",");
                int len=list.length;
                for(int i=0; i<len; i++){
                    if(!"".equals(list[i]))
                        xml_id.remove(list[i]);
                }
            }
            xml_file_ids.remove(file);
        }
    }

    public void removeXmlPath(String path) throws Exception {
        ArrayList<String> list=FileUtil.getFieldList(path);
        int len=list.size();
        for(int i=0; i<len; i++){
            removeXmlFile(list.get(i));
        }
    }

}
